package com.jiao.datasource.parse;

import lombok.Data;

import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

/**
 * sql 命令.
 * @Author Vincent.jiao
 * @Date 2022/5/13 10:20
 */
@Data
public class SQLCommand {
    //sql单元
    private SQLUnitAbstract sqlUnit;

    //命令类型
    private String commandType;

    //sql 结果
    private List<Object> result;

    //表名
    private String tableName;

    private String whereSql;

    private String colunmSql;

    public SQLCommand(){ }

    public SQLCommand(Connection conn, Statement statement, String sql){
        SQLStruct sqlStruct = SQLParse.parseSqlStruct(sql);

        if(sqlStruct == null) {
            this.sqlUnit = new UnsupportedSQLUnit(conn, statement);
        } else {
            switch (sqlStruct.getCommandType()) {
                case SQLStruct.SELECT:
                    this.sqlUnit = new ReadSQLUnit(conn, statement);
                    break;
                case SQLStruct.DELETE:
                case SQLStruct.UPDATE:
                case SQLStruct.INSERT:
                    this.sqlUnit = new WriteSQLUnit(conn, statement);
                    break;
                default:
                    //不支持类型
                    this.sqlUnit = new UnsupportedSQLUnit(conn, statement);
                    break;
            }
        }

        sqlUnit.setSql(sql);
        this.commandType = sqlStruct.getCommandType();
        this.tableName = sqlStruct.getTableName();
        this.whereSql = sqlStruct.getWhereSql();
        this.colunmSql = sqlStruct.getColunmSql();
    }
}
